
import { extendObject, renameObjectKeys } from "../functions";

export function createDeletionOptions(config = {}) {
    let { apiurl, paramName, batch, idKey, refreshMethod = 'search' } = config;

    let ids = null;

    let options = {
        methods: {
            _delete(id, cb) {
                let query = '?';

                if (typeof id !== 'object') {
                    query += `${paramName}=${id}`;
                } else if (ids && ids.length) {
                    query += `${paramName}=${ids.toString()}`
                } else {
                    return
                }

                // confirm
                this.$confirm('是否确定删除数据', '删除提示', {
                    showClose: false,
                    closeOnClickModal: false,
                    type: 'warning',
                })
                    .then(async () => {
                        await this.$delete(apiurl + query);
                        this[refreshMethod]();

                        if (cb && typeof cb === 'function') {
                            cb();
                        }
                    })
                    .catch(function () { });
            }
        }
    }

    if (batch) {
        options.methods.onSelectionChange = function (selection) {
            ids = selection.map(row => row[idKey || paramName]);
        }
    }

    return options;
}

export function createUpdateOptions(config = {}) {
    let { dialogVisibleKey = 'visible', fromDataKey = 'form', formDataKeyMapping = {}, idKey, beforeDialogOpen } = config;

    return {
        methods: {
            update(row) {
                let form = this[fromDataKey];

                if (!form) return;

                extendObject(form, renameObjectKeys(row, formDataKeyMapping));

                if ('action' in this) {
                    this.action = 'update';
                }

                this.actionObjectId = row[idKey];

                if (beforeDialogOpen) {

                    if (typeof beforeDialogOpen === 'function' && !beforeDialogOpen.call(this) || typeof beforeDialogOpen === 'string' && !this[beforeDialogOpen]()) {
                        return;
                    }
                }

                if (dialogVisibleKey in this) {
                    this[dialogVisibleKey] = true;
                }
            }
        }
    }
}